import json
import re
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import render
from utils.views import LoginRequiredJsonMixin
# Create your views here.
from django.views import View
from apps.areas.models import Area
from apps.users.models import Address, User
from django.core.cache import cache


class AreasView(View):
    def get(self, request):
        # 1、获取前端数据
        # 判断是否有缓存
        province_list = cache.get('provinces')
        if not province_list:
            # 2、查询数据
            query_set = Area.objects.filter(parent=None)
            province_list = [{'id': province.id, 'name': province.name} for province in query_set]
            # 缓存数据
            cache.set('provinces', province_list, 3600)
        # 3、返回Json数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})


class SubAreasView(View):
    def get(self, request, id):
        # 1、获取前端数据
        # 2、查询数据
        # 判断是否有缓存数据
        sub_data = cache.get('subs:%s' % id)
        if not sub_data:
            parent_model = Area.objects.get(id=id)  # 查询市或区的父级
            sub_model_list = parent_model.subs.all()
            # query_set = Area.objects.filter(parent=id)
            subs_list = [{'id': province.id, 'name': province.name} for province in sub_model_list]
            # 缓存数据
            sub_data = {
                'id': id,
                'name': parent_model.name,
                'subs': subs_list,
            }
            cache.set('subs:%s' % id, sub_data, 3600)
        # 3、返回Json数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': sub_data})


class AddressesView(LoginRequiredJsonMixin, View):
    def get(self, request):
        """
        查询收货地址
        :param request:
        :return:
        """
        # 1、获取前端数据
        # 2、查询数据
        addresses_queryset = Address.objects.filter(user=request.user, is_deleted=False)
        default_address_id = request.user.default_address_id
        # addresses = [{
        #     'id': address.id,
        #     'title': address.title,
        #     'receiver': address.receiver,
        #     'province': address.province.name,
        #     'city': address.city.name,
        #     'district': address.district.name,
        #     'place': address.place,
        #     'mobile': address.mobile,
        #     'tel': address.tel,
        #     'email': address.email,
        # } for address in addresses_queryset]
        addresses = []
        for address in addresses_queryset:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 将默认地址移动到最前面
            if default_address_id == address.id:
                # 查询集 addresses 没有 insert 方法
                addresses.insert(0, address_dict)
            else:
                addresses.append(address_dict)
        # 3、返回Json数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': addresses,
                             'default_address_id': default_address_id})

    def post(self, request):
        """
        新增收货地址
        :param request:
        :return:
        """
        # 判断是否超过20个
        count = request.user.addresses.count()
        if count >= 20:
            return JsonResponse({'code': 400, 'errmsg': '超过地址数量上限'})

        # 1、获取前端数据
        data_dict = json.loads(request.body.decode())
        receiver = data_dict.get('receiver')
        province_id = data_dict.get('province_id')
        city_id = data_dict.get('city_id')
        district_id = data_dict.get('district_id')
        place = data_dict.get('place')
        mobile = data_dict.get('mobile')
        tel = data_dict.get('tel')
        email = data_dict.get('email')
        # 2、校验数据
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式不符合要求，请重新输入'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseBadRequest('参数email有误')

        # 3、保存数据
        try:
            address = Address.objects.create(user=request.user, **data_dict)
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '数据保存失败'})
        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 4、返回Json数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})

    def put(self, request, address_id):
        """
        修改收货地址
        :param request:
        :param address_id:
        :return:
        """
        # 1、获取前端数据
        data_dict = json.loads(request.body.decode())
        title = data_dict.get('title')
        receiver = data_dict.get('receiver')
        province_id = data_dict.get('province_id')
        city_id = data_dict.get('city_id')
        district_id = data_dict.get('district_id')
        place = data_dict.get('place')
        mobile = data_dict.get('mobile')
        tel = data_dict.get('tel')
        email = data_dict.get('email')
        # 2、校验数据
        if not all([address_id, receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式不符合要求，请重新输入'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseBadRequest('参数email有误')

        # 3、保存数据
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=title,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '更新数据失败'})
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 4、返回Json数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})

    def delete(self, request, address_id):
        """
        删除收货地址
        :param request:
        :param address_id:
        :return:
        """
        # 1、获取前端数据
        # 2、校验数据
        if not address_id:
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        # 3、删除数据
        try:
            # Address.objects.filter(id=address_id).delete()
            address = Address.objects.get(id=address_id)
            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '删除数据失败'})
        # 4、返回Json数据
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class SetDefaultAddress(LoginRequiredJsonMixin, View):
    def put(self, request, address_id):
        """
        修改默认地址
        :param request:
        :param address_id:
        :return:
        """
        if not address_id:
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        try:
            # request.user.default_address_id = address_id
            # request.user.save()
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)
            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()

        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '修改默认地址失败'})
        else:
            return JsonResponse({'code': 0, 'errmsg': 'ok'})


class UpdateAddressTitle(LoginRequiredJsonMixin, View):
    def put(self, request, address_id):
        """
        修改地址标题
        :param request:
        :param address_id:
        :return:
        """
        data_dict = json.loads(request.body.decode())
        title = data_dict.get('title')
        if not all([address_id, title]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        try:
            Address.objects.filter(id=address_id).update(title=title)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '修改地址标题失败'})
        else:
            return JsonResponse({'code': 0, 'errmsg': 'ok'})
